package com.library.service.impl;

import com.library.constant.IsAdminEnum;
import com.library.constant.IsReturnEnum;
import com.library.mapper.BookMapper;
import com.library.mapper.BorrowMapper;
import com.library.mapper.UserMapper;
import com.library.pojo.entity.LibraryBooks;
import com.library.pojo.entity.LibraryBorrow;
import com.library.pojo.entity.LibraryUsers;
import com.library.service.BookService;
import com.library.pojo.dto.book.BookDTO;
import com.library.pojo.dto.book.BookPageQueryDTO;
import com.library.result.PageResult;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 图书服实现类
 */
public class BookServiceImpl implements BookService {

    private final BookMapper bookMapper;
    private final BorrowMapper borrowMapper;
    private final UserMapper userMapper;
    private final SqlSessionFactory sqlSessionFactory;

    public BookServiceImpl() {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            // 获取Mapper代理对象
            bookMapper = sqlSession.getMapper(BookMapper.class);
            borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 分页查询图书
     * @param bookPageQueryDTO 分页参数（必填：pageNum/pageSize；可选：bookId/name/author/publisher/state关键词）
     * @return PageResult<LibraryBooks>：分页图书列表
     */
    @Override
    public PageResult pageQuery(BookPageQueryDTO bookPageQueryDTO) {
        int pageNum = bookPageQueryDTO.getPageNum();
        int pageSize = bookPageQueryDTO.getPageSize();
        //pageSize代表返回多少条记录，pageNum代表返回第几页
        List<LibraryBooks> res =  bookMapper.selectBookList((pageNum - 1) * pageSize,pageSize, bookPageQueryDTO.getBookId(),
                bookPageQueryDTO.getName(), bookPageQueryDTO.getAuthor(), bookPageQueryDTO.getPublisher());
        int bookCount = bookMapper.selectBookCount();
        //封装结果集
        PageResult pageResult = new PageResult();
        pageResult.setRecords(res);
        pageResult.setTotal(bookCount);
        return pageResult;
    }

    /**
     * 根据图书编号借阅图书
     * @param bookId 图书Id
     * @return 借阅成功返回1，失败返回0
     */
    @Override
    public int borrowBook(int bookId, Integer userId) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            // 判断图书编号是否存在
            LibraryBooks book = bookMapper.selectBookById(bookId);
            if (book == null) {
//                System.out.println("要借阅的图书不存在");
                sqlSession.rollback();
                return 0;
            }
            if (book.getLoan() <= 0) {
//                System.out.println("要借阅的图书库存不足");
                sqlSession.rollback();
                return 0;
            }
            // 判断读者是否存在
            LibraryUsers libraryUsers = userMapper.selectById(userId);
            if (libraryUsers == null) {
//                System.out.println("输入读者编号有误");
                sqlSession.rollback();
                return 0;
            }
            // 判断是否是管理员
            if (libraryUsers.getIsAdmin().equals(IsAdminEnum.IS_ADMIN.getCode())) {
                sqlSession.rollback();
                return 0;
            }
            // 更新图书库存量
            book.setLoan(book.getLoan() - 1);
            int updateResult = bookMapper.updateBook(book);
            if (updateResult == 0) {
                sqlSession.rollback();
                return 0;
            }
            // 追加借阅记录
            LocalDateTime now = LocalDateTime.now();
            LibraryBorrow libraryBorrow = new LibraryBorrow();
            libraryBorrow.setBookId(bookId);
            libraryBorrow.setUserId(userId);
            libraryBorrow.setIsReturn(IsReturnEnum.NOT_RETURN.getCode());
            libraryBorrow.setBorrowTime(now);
            libraryBorrow.setReturnTime(null);

            int insertResult = borrowMapper.insertBorrow(libraryBorrow);
            if (insertResult == 0) {
                sqlSession.rollback();
                return 0;
            }
            // 提交事务
            sqlSession.commit();
            return 1;
        } catch (Exception e) {
            // 发生异常回滚事务
            sqlSession.rollback();
//            System.out.println("借阅图书过程中发生错误: " + e.getMessage());
            return 0;
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }


    /**
     * 添加图书
     * @param bookDTO 图书信息
     * @return 添加成功返回1，失败返回0
     */
    @Override
    public int insert(BookDTO bookDTO) {
        // 判断图书信息合法
        if(bookDTO.getPrice().compareTo(BigDecimal.ZERO) < 0 ||
                bookDTO.getStock() < 0 ||
                bookDTO.getLoan() < 0) {
//            System.out.println("添加图书信息不合法");
            return 0;
        }
        //创建图书类
        LibraryBooks libraryBooks = new LibraryBooks(bookDTO);
        //添加图书
        return bookMapper.insertBook(libraryBooks);
    }

    /**
     * 根据图书编号修改图书信息
     * @param bookDTO 图书信息
     * @return 成功返回1，失败返回0
     */
    @Override
    public int update(BookDTO bookDTO) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            // 获取图书信息
            LibraryBooks book = bookMapper.selectBookById(bookDTO.getBookId());
            // 判断图书信息是否存在
            if(book == null) {
//                System.out.println("要修改的图书不存在");
                return 0;
            }
            // 判断图书信息合法
            if(bookDTO.getPrice().compareTo(BigDecimal.ZERO) < 0 || bookDTO.getStock() < 0) {
//                System.out.println("修改图书属性不合法");
                return 0;
            }
            if(bookDTO.getLoan() > bookDTO.getStock()) {
//                System.out.println("修改图书属性不合法");
                return 0;
            }
            //创建图书类
            LibraryBooks libraryBooks = new LibraryBooks(bookDTO);
            //修改图书信息
            int flag = bookMapper.updateBook(libraryBooks);
            //修改图书信息不存在
            if(flag == 0) {
//                System.out.println("要修改的图书不存在");
            }
            // 提交事务
            sqlSession.commit();
            return flag;
        } catch (Exception e) {
            // 发生异常回滚事务
            sqlSession.rollback();
//            System.out.println("修改图书过程中发生错误: " + e.getMessage());
            return 0;
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }

    /**
     * 根据图书编号删除图书
     * @param bookId 图书编号
     * @return 成功返回1，失败返回0
     */
    @Override
    public int deleteById(Integer bookId) {
        int flag =  bookMapper.deleteBook(bookId);
        if(flag == 0) {
//            System.out.println("要删除的图书不存在");
        }
        return flag;
    }
}
